package com.mock.ems.controller.config;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.DateUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;

import java.util.*;

/**
 * Created by MOCK on 2017/8/23.
 */
public class UnionController extends Controller {

    public void index() {

        List<Record> btypeList = Db.find("select id,title from join_sort where parent_id = 0");
        if (CollectionUtil.isNotEmpty(btypeList)) {
            btypeList.forEach(item -> {
                Long parentId = item.getLong("id");
                List<Record> stypeList = Db.find("select id,title from join_sort where parent_id = ? ",parentId);
                item.set("stypeList",stypeList);
            });
            setAttr("btypeList",btypeList);
        }

        Record config = Db.findFirst("select * from join_config");
        if (null != config) {
            setAttr("union",config.getColumns());
        }
        renderJsp("/page/config/union/union_list.jsp");
    }

    public void edit() {

        Long id = getParaToLong("id");
        if (null != id) {
            Record record = Db.findById("join_article",id);
            if (null != record) {
                setAttr("record",record.getColumns());
                Long sort_id = record.getLong("sort_id");
                Record unionSort = Db.findById("join_sort",sort_id);
                if (null != unionSort) {
                    Long parent_id = unionSort.getLong("parent_id");
                    if (parent_id > 0) {
                        //加载小类
                        List<Record> stypeRecordList = Db.find("select id,title from join_sort where parent_id = ? ",parent_id);
                        setAttr("stypeRecordList",stypeRecordList);
                        setAttr("parent_id",parent_id);
                        setAttr("stype_id",sort_id);
                    }else {
                        //加载小类
                        List<Record> stypeRecordList = Db.find("select id,title from join_sort where parent_id = ? ",sort_id);
                        setAttr("stypeRecordList",stypeRecordList);
                        setAttr("parent_id",sort_id);
                    }
                }
            }
        }
        List<Record> btypeList = Db.find("select id,title from join_sort where parent_id = 0");
        setAttr("btypeList",btypeList);
        renderJsp("/page/config/union/union_edit.jsp");
    }

    public void pagination() {

        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        String selecSQL = "select id,sort_id,title,description,create_time,status";

        StringBuilder exceptSelectSQL = new StringBuilder(" from join_article where 1 = 1 ");
        List<Object> params = new ArrayList<Object>();

        Date begin_time = DateUtil.parseToDate(getPara("begin_time"),DateUtil.FULL_PATTERN);
        Date end_time = DateUtil.parseToDate(getPara("end_time"),DateUtil.FULL_PATTERN);


        String title = getPara("title");
        if (StringUtil.isNotEmpty(title)) {
            exceptSelectSQL.append(" and title like ? ");
            params.add('%' + title.trim() + '%');
        }

        if (null != begin_time && end_time == null) {
            exceptSelectSQL.append(" and create_time >= ? ");
            params.add(begin_time);
        }

        if (null == begin_time && end_time != null) {
            exceptSelectSQL.append(" and create_time <= ? ");
            params.add(end_time);
        }

        if (null != begin_time && null != end_time) {
            exceptSelectSQL.append(" and create_time >= ? and create_time <= ? ");
            params.add(begin_time);
            params.add(end_time);
        }


        exceptSelectSQL.append(" order by update_time desc ");
        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, selecSQL, exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, selecSQL, exceptSelectSQL.toString(),params.toArray());
        }

        if (CollectionUtil.isNotEmpty(recordList.getList())) {
            recordList.getList().forEach(item -> {
                Long sortId = item.getLong("sort_id");
                String title0 = Db.queryStr("select title from join_sort where id = ? ",sortId);
                item.set("type_str",title0);
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }


    @Before(Tx.class)
    public void publish() {

        Long id = getParaToLong("id");
        if (null == id) {
            renderJson(new JsonResult().status("-1"));
            return;
        }
        if (Db.update("update join_article set status = 1,update_time = ? where id = ? ",new Date(),id) <= 0) {
            renderJson(new JsonResult().status("-2"));
            return;
        }
        renderJson(new JsonResult().status("000"));
    }

    @Before(Tx.class)
    public void save() {

        Long id = getParaToLong("id");
        Record record = null;
        if (null == id) {
            record = new Record();
            record.set("status",0)
                    .set("create_time",new Date());
        }else {
            record = Db.findById("join_article",id);
        }
        if (null == record) {
            renderJson(new JsonResult().status("-1"));
            return;
        }

        record.set("sort_id",getPara("sort_id"))
                .set("title",getPara("title"))
                .set("image",getPara("image"))
                .set("description",getPara("description"))
                .set("content",getPara("content"))
                .set("update_time",new Date())
                .set("hot",getPara("hot"))
                .set("commend",getPara("commend"));

        if (null == id) {
            if (!Db.save("join_article",record)) {
                renderJson(new JsonResult().status("-2"));
                return;
            }
        }else {
            if (!Db.update("join_article",record)) {
                renderJson(new JsonResult().status("-3"));
                return;
            }
        }
        renderJson(new JsonResult().status("000"));
    }


    public void typeEdit() {

        List<Record> btypeList = Db.find("select id,title from join_sort where parent_id = 0");
        setAttr("btypeList",btypeList);

        Record btype = Db.findById("join_sort",getPara("id"));
        if (null != btype) {
            setAttr("btype",btype.getColumns());
        }

        List<Record> childRecodList = Db.find("select id,title,icon from join_sort where parent_id = ? ",getPara("id"));
        if (CollectionUtil.isNotEmpty(childRecodList)) {
            setAttr("childTypeList",childRecodList);
        }
        renderJsp("/page/config/union/btype_edit.jsp");
    }

    public void typeAdd() {

        renderJsp("/page/config/union/btype_add.jsp");
    }


    public void stype() {

        Long parent_id = getParaToLong("parent_id");
        List<Record> recordList = Db.find("select id,title from join_sort where parent_id = ? ",parent_id);
        List<Map<String,Object>> stypeMapList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recordList)) {
            recordList.forEach(item -> {
                stypeMapList.add(item.getColumns());
            });
        }
        renderJson(stypeMapList);
    }


    @Before(Tx.class)
    public void bannerSave() {

        String banners = getPara("banners");
        String urls = getPara("bannerUrls");

        Db.update("delete from join_config");

        Record record = new Record();
        record.set("banners",banners)
                .set("urls",urls);
        if (Db.save("join_config",record)) {
            renderJson(new JsonResult().status("000"));
        }else {
            renderJson(new JsonResult().status("-1"));
        }
    }


    @Before(Tx.class)
    public void btypeSave() {

        String btype = getPara("btype");
        String icon = getPara("icon");
        String banners = getPara("banners");
        String urls = getPara("bannerUrls");

        Record parentRecord = new Record();
        parentRecord.set("parent_id",0)
                .set("title",btype)
                .set("status",1)
                .set("icon",icon)
                .set("banners",banners)
                .set("urls",urls)
                .set("create_time",new Date())
                .set("update_time",new Date());
        if (!Db.save("join_sort",parentRecord)) {
            renderJson(new JsonResult().status("-1"));
            return;
        }

        renderJson(new JsonResult().status("000"));
    }


    @Before(Tx.class)
    public void typeSave() {
        Long id = getParaToLong("id");
        if (null == id) {
            renderJson(new JsonResult().status("-1"));
            return;
        }

        //删除
        Db.update("delete from join_sort where parent_id = ? ",id);

        String stypes = getPara("stypes");
        if (StringUtil.isNotEmpty(stypes)) {
            String [] stypesArray = stypes.split(",");
            String [] stypeImgArray = getPara("typeBanners").split(",");
            if (null == stypesArray || stypesArray.length == 0) {
                renderJson(new JsonResult().status("-4"));
                return;
            }

            for (int i = 0;i < stypesArray.length;i++) {
                Record record = new Record();
                record.set("parent_id",id)
                        .set("title",stypesArray[i])
                        .set("status",1)
                        .set("icon",stypeImgArray[i])
                        .set("create_time",new Date())
                        .set("update_time",new Date());
                if (!Db.save("join_sort",record)) {
                    throw new RuntimeException("save join_sort fail");
                }
            }
        }
        renderJson(new JsonResult().status("000"));
    }

    @Before(Tx.class)
    public void delete() {

        String articleIdList = getPara("articleIdList");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(articleIdList)) {
            renderJson(result.status("001").show("删除失败"));
            return;
        }

        StringBuilder deleteSQL = new StringBuilder("delete from join_article where id in (");
        Object [] articles = new Object[articleIdList.split(",").length];
        int index = 0;
        for (String id : articleIdList.split(",")) {
            deleteSQL.append("?,");
            articles[index]= id;
            index ++;
        }
        deleteSQL.deleteCharAt(deleteSQL.length() - 1).append(")");


        boolean deleteResult = Db.update(deleteSQL.toString(),articles) == articles.length;
        renderJson(deleteResult ? result.status("000").show("删除成功"):result.status("002").show("删除失败"));
    }

}
